package com.xpalive.utils;

import java.math.BigDecimal;
import java.util.Deque;
import java.util.LinkedList;
import lombok.Getter;


public class SortArrIndex {

    //存储数据
    @Getter
    private final Deque<BigDecimal> que;
    //存储排序时弹出的数据
    private final Deque<BigDecimal> d;

    //存储数据的下标
    @Getter
    private final Deque<Integer> indexQue;
    //存储排序时弹出的数据的下标
    private final Deque<Integer> indexD;

    //待排序的数据
    private final BigDecimal[] arr;

    private final boolean reverse;

    public SortArrIndex(BigDecimal[] arr, boolean reverse) {
        this.arr = arr;
        this.que = new LinkedList<>();
        this.d = new LinkedList<>();
        this.indexQue = new LinkedList<>();
        this.indexD = new LinkedList<>();
        this.reverse = reverse;
        sort();
    }

    public SortArrIndex(BigDecimal[] arr) {
        this(arr, false);
    }

    public void sort() {
        //依次压入数据
        for (int i = 0; i < arr.length; i++) {
            push(arr[i], i);
        }
    }

    private void push(BigDecimal bigDecimal, Integer index) {
        //如果为空则直接压入栈
        if (que.isEmpty()) {
            que.offerFirst(bigDecimal);
            indexQue.offerFirst(index);
        } else {
            //如果栈顶数据小于待压入数据则直接压入
            if (reverse ? que.peekFirst().compareTo(bigDecimal) > 0
                : que.peekFirst().compareTo(bigDecimal) < 0
            ) {
                que.offerFirst(bigDecimal);
                indexQue.offerFirst(index);
            } else {
                //弹出栈顶数据
                BigDecimal poll = que.pollFirst();
                Integer indexPoll = indexQue.pollFirst();
                if (poll != null) {
                    //保存在临时栈中
                    d.offerFirst(poll);
                    indexD.offerFirst(indexPoll);
                }
                //再次压入数据
                push(bigDecimal, index);
            }
        }
        //数据压入成功后,临时栈中如果有数据则压回栈中
        while (!d.isEmpty()) {
            que.offerFirst(d.pollFirst());
            indexQue.offerFirst(indexD.pollFirst());
        }
    }

}
